package rs.dalao.syc.passport.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import rs.dalao.syc.passport.dao.persist.repository.IUserRepository;
import rs.dalao.syc.passport.pojo.vo.LoginInfoVO;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private IUserRepository userRepository;
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        LoginInfoVO loginInfo = userRepository.getInfo(userName);
        if(loginInfo==null){
            throw new UsernameNotFoundException("User not found with username: " + userName);
        }

        List<String> permissions = loginInfo.getPermissions();
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        for (String permission : permissions) {
            GrantedAuthority authority = new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }

        CustomUserDetails userDetails = new CustomUserDetails(
                loginInfo.getId(),
                loginInfo.getRole(),
                loginInfo.getAvatar(),
                loginInfo.getUserName(),
                loginInfo.getName(),
                loginInfo.getPassword(),
                loginInfo.getEnable()==1,
                authorities);
        return userDetails;
    }
}
